'use strict'

const { v4: uuidv4 } = require('uuid')
const AdminApiController = require('../../common/admin')
const admin = require('./system/admin')

class Controller extends AdminApiController {
  get Model() {
    return this.ctx.model.Cdk
  }

  // 列表查询前
  beforeIndex() {
    const { ctx } = this
    const { query, helper } = ctx
    const { admin } = ctx.state
    const filter = {}

    if (!admin.isAdmin)
      filter.adminId = admin.adminId

      // 匹配搜索
    ;[''].map((key) => {
      if (query[key] && !query[key] == '') filter[key] = query[key]
    })

    // 关键字模糊查询
    if (query.keyword && !query.keyword == '') filter.title = new RegExp(helper.toMongoRegex(query.keyword, 'i'))

    return {
      filter,
      // sort: {
      //   isTop: 'DESC',
      //   rank: 'ASC',
      // },
    }
  }

  async create() {
    const { ctx } = this
    const { body } = ctx.request
    const { helper } = ctx
    const { admin } = ctx.state

    helper.validate(body, {
      required: ['number'],
    })

    // const unitPrice = 0.8
    // if (!this.isSuperAdmin) {
    //   const agent = await ctx.model.Agent.findOne({ adminId: admin.adminId })

    //   if (!agent || agent.state) throw '账号异常'

    //   const cost = unitPrice * body.number
    //   if (agent.money < cost) throw `余额不足${cost}元`

    //   await ctx.model.Agent.updateOne(
    //     { _id: agent._id },
    //     {
    //       $inc: {
    //         money: 0 - cost,
    //       },
    //     }
    //   )
    // }

    const data = []

    for (let i = 0; i < body.number; i++) {
      data.push({
        cdk: uuidv4(),
        type: body.body,
        game: body.game,
        state: 0,
        adminId: admin.adminId,
        // cost: unitPrice,
      })
    }

    // 增加用户积分
    await ctx.model.Cdk.insertMany(data)
  }
}

module.exports = Controller
